# coding: utf-8
import json
import logging
import re
import threading
from http.cookiejar import CookieJar
import random
import jsonpath
import requests
from bs4 import BeautifulSoup

from core import JZ_part3


class JZThread(threading.Thread):
    def __init__(self, username, password):
        threading.Thread.__init__(self)
        self.username = username
        self.password = password

    def run(self):
        self.getjz()

    def getjz(self):
        try:
            logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
            logger = logging.getLogger(__name__)
            login_url = 'http://zhxg.njcit.cn/xsfw/sys/emapfunauth/casValidate.do?service=%2Fxsfw%2Fsys%2Fxggzptapp%2Findex.do'  #cas登录网址，登陆成功后会跳转到智慧学工
            user_agent_list = [
                "Mozilla/5.0 (Windows; U; Windows CE) AppleWebKit/534.46.6 (KHTML, like Gecko) Version/4.1 Safari/534.46.6",
                "Mozilla/5.0 (compatible; MSIE 9.0; Windows 95; Trident/5.1)",
                "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_1; rv:1.9.3.20) Gecko/2018-12-28 03:09:41 Firefox/3.6.10",
                "Mozilla/5.0 (Windows NT 6.0) AppleWebKit/534.2 (KHTML, like Gecko) Chrome/33.0.846.0 Safari/534.2",
                "Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 5.0; Trident/3.0)",
                "Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 5.0; Trident/5.1)",
                "Opera/9.11.(Windows NT 6.0; sk-SK) Presto/2.9.173 Version/12.00",
                "Mozilla/5.0 (Windows NT 4.0) AppleWebKit/532.1 (KHTML, like Gecko) Chrome/35.0.840.0 Safari/532.1",
                "Mozilla/5.0 (iPod; U; CPU iPhone OS 3_1 like Mac OS X; sr-ME) AppleWebKit/535.34.2 (KHTML, like Gecko) "
                "Version/3.0.5 Mobile/8B117 Safari/6535.34.2",
                "Mozilla/5.0 (iPhone; CPU iPhone OS 4_2_1 like Mac OS X) AppleWebKit/536.2 (KHTML, like Gecko) "
                "CriOS/16.0.877.0 Mobile/76I352 Safari/536.2",
            ]#随机User-Agent
            login_headers = {'Connection': 'close', 'User-Agent': random.choice(user_agent_list),
                             'Accept-Language': 'zh-CN,zh;q=0.9'}#随机headers
            session_request = requests.session()#创建session会话
            session_request.cookies = CookieJar()#记录cookie，方便之后的抢讲座操作
            code_result = session_request.get(login_url, headers=login_headers, timeout=5)#获取cas登录界面
            code_html = code_result.content.decode('utf-8')
            code_dic = {}
            bs1 = BeautifulSoup(code_html, 'html.parser')
            for line in bs1.form.findAll('input'):
                if line.attrs['name'] is not None:
                    code_dic[line.attrs['name']] = line.attrs['value']
            # 获取登录需要的参数，使用session可以保持会话
            login_data = dict(username=self.username, password=self.password, captcha='', warn='true',
                              lt=code_dic['lt'],
                              execution=code_dic['execution'], _eventId=code_dic['_eventId'])
            login_result = session_request.post(code_result.url, data=login_data, headers=login_headers, timeout=5)
            #进行登录操作
            # print(login_result.url)
            # print(re.search('cas',login_result.url ))
            if re.search('cas', login_result.url) is None:
                # logger.info("学号：" + username + ' 登录成功！')
                zhxg_url = 'http://zhxg.njcit.cn/xsfw/sys/xgutilapp/indexmenu/getAppConfig.do?appId=5851052168076122&appName=xggzptapp '
                zhxg_data = {
                    "appId": "5851052168076122",
                    "appName": "xggzptapp",
                }
                zhxg_result = session_request.post(zhxg_url, data=zhxg_data, headers=login_headers, verify=False,
                                                   timeout=5)
                #由于智慧学工是动态加载，故需要发送此请求来获取cookie，以此得到抢讲座时需要的cookie
                loadjz_url = 'http://zhxg.njcit.cn/xsfw/sys/jzglappnjcit/modules/jzll/cxyfbhd.do'
                loadjz_data = {
                    'XSBH': self.username,
                    'XSBH1': self.username,
                    'querySetting': '[{"caption":"","name":"XN","value":"2020","builder":"equal","linkOpt":"AND"},'
                                    '{"caption":"","name":"XQ","value":"2","builder":"equal","linkOpt":"AND"},{"name":"XSBH",'
                                    '"value":"190410224","linkOpt":"AND","builder":"equal"},{"name":"XSBH1",'
                                    '"value":"190410224","linkOpt":"AND","builder":"equal"}]',
                    'pageSize': '10',
                    'pageNumber': '1'
                }
                jz_result = session_request.post(loadjz_url, data=loadjz_data, headers=login_headers, timeout=5)
                # 获取抢讲座第一页的讲座信息
                jzinf = jz_result.content.decode('utf-8')
                jzinf_json = json.loads(jzinf)#将获取到的讲座信息转化为json格式
                getjz_url = 'http://zhxg.njcit.cn/xsfw/sys/jzglappnjcit/modules/jzsq/xshdbm.do'#报名讲座的url
                checkurl = '$.datas.cxyfbhd.rows[*]'
                jz_name = jsonpath.jsonpath(jzinf_json, checkurl + '.JZTM')
                jz_wid = jsonpath.jsonpath(jzinf_json, checkurl + '.WID')
                #获取讲座的名称和唯一编码(wid)
                # print(jz_wid)
                for jz1 in range(len(jz_wid)):
                    wid = jz_wid[jz1]
                    name = jz_name[jz1]
                    thread1 = JZ_part3.JZThread(self.username, wid, name, session_request, getjz_url, login_headers)
                    thread1.start()
                    thread1.join()
                #创建多线程来报名第一页的所有讲座
            else:
                logger.warning('学号：' + self.username + '登录失败')
                exit('-1')
        except Exception as err:
            logger.warning(err)
